/*******************************************************************************
 * Copyright (c) 2012, G. Weirich and Elexis
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    G. Weirich - initial implementation
 *******************************************************************************/

package ch.elexis.easy.ui.widgets;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;

import ch.elexis.core.data.IAttribute;

/**
 * A Text that is bound to an Attribute of an IPersistentObject. Includes check of the input against
 * a pattern to match
 * 
 * @author gerry
 * 
 */
public class BoundText extends BoundField {
	Pattern pattern;
	FieldDecoration errorFieldIndicator, okFieldIndicator;
	ControlDecoration cd;
	
	/**
	 * Constructor
	 * 
	 * @param parent
	 *            parent composite
	 * @param field
	 *            attribute to link
	 * @param acceptablePattern
	 *            Regexp for acceptable input. Can be null, then all input is acceptable für text
	 *            attributes and all numeric input is acceptable for integral anttributes.
	 */
	public BoundText(Composite parent, IAttribute field, String acceptablePattern){
		super(parent, field);
		
		if (acceptablePattern == null) {
			if (field.getType().equals(IAttribute.type.INTEGRAL)) {
				pattern = Pattern.compile("[0-9\\.\\,]*");
			}
		} else {
			pattern = Pattern.compile(acceptablePattern);
		}
		if (pattern != null) {
			errorFieldIndicator =
				FieldDecorationRegistry.getDefault().getFieldDecoration(
					FieldDecorationRegistry.DEC_ERROR);
			
			cd = new ControlDecoration(getWidget(), SWT.LEFT | SWT.TOP);
			cd.setImage(errorFieldIndicator.getImage());
			cd.setDescriptionText(errorFieldIndicator.getDescription());
			((Text) getWidget()).addModifyListener(new ModifyListener() {
				
				@Override
				public void modifyText(ModifyEvent event){
					// TODO Auto-generated method stub
					Matcher m = pattern.matcher(((Text) getWidget()).getText());
					if (m.matches()) {
						cd.hide();
					} else {
						cd.show();
					}
				}
				
			});
		}
	}
	
}
